package com.maoxx.humanresourcemanage_service.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maoxx.humanresourcemanage_service.dto.Response;
import com.maoxx.humanresourcemanage_service.dto.ResponseDTO;
import com.maoxx.humanresourcemanage_service.entity.Menu;
import com.maoxx.humanresourcemanage_service.entity.RoleMenu;
import com.maoxx.humanresourcemanage_service.entity.StaffRole;
import com.maoxx.humanresourcemanage_service.mapper.MenuMapper;
import com.maoxx.humanresourcemanage_service.utils.HutoolExcelUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @className: MenuService
 * @author: Maoxx
 * @date: 2024/11/11 13:35
 * @Version: 1.0
 * @description:
 */

@Service
public class MenuService extends ServiceImpl<MenuMapper, Menu> {

    @Resource
    private StaffRoleService staffRoleService;

    @Resource
    private RoleMenuService roleMenuService;


    /**
     * 该函数的主要作用是根据提供的员工ID，查询并返回该员工所拥有的菜单权限列表。
     *
     * @param id 员工ID
     * @return ResponseDTO
     */
    public ResponseDTO getStaffMenu(Integer id) {
        Set<Menu> set = new HashSet<>();
        List<StaffRole> roleList = staffRoleService.list(new QueryWrapper<StaffRole>().eq("staff_id", id));

        for (StaffRole staffRole : roleList) {
            List<RoleMenu> roleMenuList = roleMenuService.list(new QueryWrapper<RoleMenu>()
                    .eq("role_id", staffRole.getRoleId()).eq("status", 1));

            for (RoleMenu roleMenu : roleMenuList) {
                List<Menu> menuList = list(new QueryWrapper<Menu>().eq("id", roleMenu.getMenuId()));
                set.addAll(menuList);
            }
        }
        List<Menu> menus = new ArrayList<>(set);
        // 根据获得的菜单，为父级菜单设置子菜单
        return Response.success(setSubMenu(menus));
    }

    /**
     * 为父级菜单设置子菜单，使用流来处理数据，并返回父级菜单
     *
     * @param list 菜单列表
     * @return List<Menu>
     */
    public List<Menu> setSubMenu(List<Menu> list) {
        // 父级菜单
        List<Menu> parentList = list.stream().parallel()
                .filter(menu -> menu.getParentId() == 0).collect(Collectors.toList());
        for (Menu parentMenu : parentList) {
            // 子菜单
            List<Menu> subList = list.stream().parallel()
                    .filter(menu -> menu.getParentId() == parentMenu.getId()).collect(Collectors.toList());
            parentMenu.setChildren(subList);
        }
        return parentList;
    }

    /**
     * 查找所有菜单
     *
     * @return
     */
    public ResponseDTO findAll() {
        List<Menu> list = list();
        // 为父级菜单设置子菜单
        return Response.success(setSubMenu(list));
    }

    public ResponseDTO export(HttpServletResponse response) throws IOException {
        List<Menu> list = list();
        HutoolExcelUtil.writeExcel(response, list, "菜单", Menu.class);
        return Response.success();
    }


    /**
     * 导入数据
     *
     * @param file 文件/excel
     * @return ResponseDTO
     * @throws IOException 异常
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO imp(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        // 读取excel
        List<Menu> menus = HutoolExcelUtil.readExcel(inputStream, 1, Menu.class);
        // 批量保存
        if (saveBatch(menus)) {
            return Response.success();
        }
        return Response.error();
    }

    /**
     * 分页查询
     * @param current 当前页
     * @param size 每页大小
     * @param name 菜单名称
     * @return ResponseDTO
     */
    public ResponseDTO list(Integer current, Integer size, String name) {
        IPage<Menu> config = new Page<>(current, size);

        QueryWrapper<Menu> qw = new QueryWrapper<>();
        if (name != "" && name != null) {
            qw.like("name", name);
        }

        qw.eq("parent_id", 0); // 查询父级菜单
        IPage<Menu> page = page(config, qw);
        // 查询所有菜单
        List<Menu> list = list();
        // 父级菜单
        List<Menu> parentList = page.getRecords();

        for (Menu parentMenu : parentList) {
            // 设置子菜单
            List<Menu> subList = list.stream().filter(
                    menu -> menu.getParentId() == parentMenu.getId()
            ).collect(Collectors.toList());
            parentMenu.setChildren(subList);
        }

        // 将响应数据填充到map中
        Map<String,Object> map = new HashMap<>();
        map.put("pages", page.getPages());
        map.put("total", page.getTotal());
        map.put("list", page.getRecords());
        return Response.success(map);

    }

    public ResponseDTO deleteOne(Integer id) {
        if (removeById(id)) {
            return Response.success();
        }
        return Response.error();
    }

    public ResponseDTO deleteBatch(List<Integer> ids) {
        if (removeByIds(ids)) {
            return Response.success();
        }
        return Response.error();
    }

    public ResponseDTO add(Menu menu) {
        if (save(menu)) {
            return Response.success();
        }
        return Response.error();
    }

    public ResponseDTO edit(Menu menu) {
        if (updateById(menu)) {
            return Response.success();
        }
        return Response.error();
    }
}
